package com.cj.picturebackend.aop;

import com.cj.picturebackend.annotation.AuthCheck;
import com.cj.picturebackend.constant.UserConstant;
import com.cj.picturebackend.exception.BusinessException;
import com.cj.picturebackend.exception.ErrorCode;
import com.cj.picturebackend.exception.ThrowUtils;
import com.cj.picturebackend.model.entity.User;
import com.cj.picturebackend.model.enums.UserRoleEnum;
import com.cj.picturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author cc
 * @date 2025-04-07 15:59
 **/
@Aspect
@Component
public class AuthCheckAspect {

    @Resource
    private UserService userService;
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        User loginUser = userService.getLoginUser(request);

        // 判断是否有权限
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);

        if (mustRoleEnum == null){
            return joinPoint.proceed();
        }

        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        ThrowUtils.throwIf(userRoleEnum==null, ErrorCode.NO_AUTH_ERROR);


        // 必须要管理员
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        return joinPoint.proceed();
    }
}
